
const express=require("express");
const Users= require("../models/users");
const jwt=require("jsonwebtoken");
const cookieParser=require("cookie-parser");
const secret="jni";
const router=new express.Router();

router.use(cookieParser());

router.post("/register", async(req,res)=>{
    console.log(req.body);
    const {
        user_name,
        password
    }=req.body;

    const user_name_reg=/^[A-z0-9]{3,12}$/;
    const password_reg=/^[A-z0-9]{3,12}$/;

    if(user_name_reg.test(user_name.trim()) && password_reg.test(password.trim())){
        //查询是否有user_name
        const result_find=await Users.findOne({
            user_name
        });
        
        console.log(result_find);
        if(result_find){
            res.send('用户名已存在');
        }else{
            const result =await Users.create({
                user_name,
                password
            })
            console.log(result);
        }
        res.send('注册成功!');
    }else{
        res.send("用户名或者密码不配！！")
    }

})
router.post("/login",async(req,res)=>{
    //将网页的数据存到user
    const user=req.body;

    const result=await Users.findOne({
        user_name:user.user_name
    },{
        _id:0,
        __v:0
    })
    console.log(result);
    if(result){
        if(user.user_name == result.user_name && user.password == result.password){
            // user.exp=user.exp=Date.now()+1000*60*60*24*7;
            jwt.sign(user,secret,{
                expiresIn:'1h'
            },(err,token)=>{
                if(!err){
                    console.log(token);
                    res.cookie('token',token,{
                        maxAge:1000*60*60*24*7
                    })
                    res.send("登录成功！！")
                }else {
                    console.log(err);
                    res.send("用户名或密码错误");
                }
            })
        }else{
            res.send("用户名或密码错误");
        }
    }else{
        res.send("用户名或密码错误");
    }
})
router.get('/tokenTest',(req,res)=>{
    console.log(req.cookies);
    jwt.verify(req.cookies.token,secret,(err,data)=>{
        if(!err){
            console.log(data);
            res.send("获取到cookies");
        }else{
            console.log(err);
            res.send('请去登录页面重新登录')
        }
    })
})
module.exports= router;